package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.ManagerConstants;
import com.powernode.domain.SysRole;
import com.powernode.domain.SysRoleMenu;
import com.powernode.mapper.SysRoleMapper;
import com.powernode.mapper.SysRoleMenuMapper;
import com.powernode.service.SysRoleMenuService;
import com.powernode.service.SysRoleService;
import com.powernode.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = "com.powernode.service.impl.SysRoleServiceImpl")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;


    /**
     * 查询系统所有角色
     * 全量查询，将所有数据存放在缓存中
     *
     * @return
     */
    @Override
    @Cacheable(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    public List<SysRole> querySysRoleList() {
        return sysRoleMapper.selectList(new LambdaQueryWrapper<SysRole>()
                .orderByDesc(SysRole::getCreateTime));
    }

    /**
     * 新增角色
     * 1. 新增角色与权限的关系集合
     * 2. 新增角色
     * @param sysRole
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    public Boolean savaSysRole(SysRole sysRole) {
        sysRole.setCreateTime(new Date());
        sysRole.setCreateUserId(AuthUtils.getLoginUserId());
        int insert = sysRoleMapper.insert(sysRole);
        if(insert > 0) {
//            新增角色与权限的关系记录
            Long roleId = sysRole.getRoleId();
//            获取角色对应的权限id集合
            List<Long> menuIdList = sysRole.getMenuIdList();
//            判断是否有值
            List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(menuIdList) && menuIdList.size() != 0) {
//                遍历权限id集合
                menuIdList.forEach(menuId -> {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setRoleId(roleId);
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenus.add(sysRoleMenu);
                });
                //            批量添加角色和权限关系集合
                sysRoleMenuService.saveBatch(sysRoleMenus);
            }

        }
        return insert > 0;
    }


    /**
     * 查询角色信息
     * @param roleId 角色标识
     * @return
     */
    @Override
    public SysRole querySysRoleInfoByRoleId(Long roleId) {
        SysRole sysRole = sysRoleMapper.selectById(roleId);
//        根据角色标识查询查询角色与权限的关系集合
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId));

//        判断是否有值
        if(CollectionUtil.isNotEmpty(sysRoleMenus) && sysRoleMenus.size() != 0) {
            List<Long> menuIdList = sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
            sysRole.setMenuIdList(menuIdList);
        }
        return sysRole;
    }

    /**
     * 修改角色信息
     * @param sysRole 角色信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    public Boolean modifySysRole(SysRole sysRole) {
        Long roleId = sysRole.getRoleId();
//        删除角色原来的权限集合
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId));

//            新增角色与权限的关系记录
//            获取角色对应的权限id集合
        List<Long> menuIdList = sysRole.getMenuIdList();
//            判断是否有值
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(menuIdList) && menuIdList.size() != 0) {
//                遍历权限id集合
            menuIdList.forEach(menuId -> {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenus.add(sysRoleMenu);
            });
            //            批量添加角色和权限关系集合
            sysRoleMenuService.saveBatch(sysRoleMenus);
        }
//        根据角色信息
        return sysRoleMapper.updateById(sysRole) > 0;

    }

    /**
     * 批量删除角色信息
     * @param roleIdList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    public Boolean removeSysRoleListByIds(List<Long> roleIdList) {
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>()
                .in(SysRoleMenu::getRoleId, roleIdList));
        return sysRoleMapper.deleteBatchIds(roleIdList) == roleIdList.size();
    }
}
